package gui;

import java.util.ArrayList;

/**
 * @author Ramy Refky 
 * */
public class WiringGrid {

	MainGui mg;
	ArrayList<Wire> wires;
	
	/**
	 * Constructor initializes WiringGrid Class, which stores the wires in the workArea.
	 * @param MainGui
	 * */
	public WiringGrid(MainGui mg){
		this.mg=mg;
		wires=new ArrayList<Wire>();
	}
	/**
	 * Deletes a given wire.
	 * */
	public void deleteWire(Wire w){
		ComponentPin firstPin=w.getFirstPin();
		ComponentPin secondPin=w.getSecondPin();
		
		if(w.isGrouped()){
			if(firstPin.getType()){
				ArrayList<ComponentPin> firstpins = firstPin.getParentComponent().getOutputPins();
				for(int i=0;i<firstpins.size();i++){
					firstpins.get(i).removeConnection();
				}
			}
			if(!firstPin.getType()){
				ArrayList<ComponentPin> firstpins = firstPin.getParentComponent().getInputPins();
				for(int i=0;i<firstpins.size();i++){
					firstpins.get(i).removeConnection();
				}
			}
			if(secondPin.getType()){
				ArrayList<ComponentPin> secondpins = secondPin.getParentComponent().getOutputPins();
				for(int i=0;i<secondpins.size();i++){
					secondpins.get(i).removeConnection();
				}
			}
			if(!secondPin.getType()){
				ArrayList<ComponentPin> secondpins = secondPin.getParentComponent().getInputPins();
				for(int i=0;i<secondpins.size();i++){
					secondpins.get(i).removeConnection();
				}
			}
		}else{
			firstPin.removeConnection();
			secondPin.removeConnection();
		}
		
		wires.remove(w);
		mg.getWorkArea().removeWire(w);
	}
	/**
	 * Deletes all wires connected to a given ComponentPin.
	 * */
	public void deleteWire(ComponentPin pin){
		for(int i=0;i<wires.size();i++){
			if(wires.get(i).getFirstPin().equals(pin)||
					wires.get(i).getSecondPin().equals(pin)){
				
				deleteWire(wires.get(i));
				i--;
			}
		}
	}
	/**
	 * Adds a wire to the WiringGrid.
	 * */
	public void addWire(Wire w){
		wires.add(w);
	}
	/**
	 * Gets all wires in the WiringGrid.
	 * @return ArrayList
	 * */
	public ArrayList<Wire> getWires(){
		return wires;
	}
}
